package com.lkd.handler;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.lkd.business.MsgHandler;
import com.lkd.common.VMSystem;
import com.lkd.config.TopicConfig;
import com.lkd.contract.VendoutContract;
import com.lkd.contract.VendoutData;
import com.lkd.contract.VendoutResultContract;
import com.lkd.emq.Topic;
import com.lkd.entity.OrderEntity;
import com.lkd.service.OrderService;
import com.lkd.utils.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.io.IOException;

import static com.lkd.common.VMSystem.*;

/**
 * @author brianxia
 * @version 1.0
 * @date 2022-07-22 16:16
 */
@Component
@Topic(TopicConfig.VMS_RESULT_TOPIC)
@Slf4j
public class VendoutCompleteHandler implements MsgHandler {

    @Autowired
    private OrderService orderService;


    @Override
    @Transactional
    public void process(String jsonMsg) throws IOException {
        //1.反序列化
        VendoutResultContract contract = JsonUtil.getByJson(jsonMsg, VendoutResultContract.class);
        VendoutData vendoutData = contract.getVendoutData();
        if(vendoutData == null || StringUtils.isEmpty(vendoutData.getOrderNo())
          || StringUtils.isEmpty(vendoutData.getChannelCode())  || vendoutData.getSkuId() == 0){
            log.error("出货结果消息处理报错,消息内容:" + jsonMsg);
            return;
        }

        //2.更新数据库状态
        orderService.update(Wrappers.<OrderEntity>lambdaUpdate()
                .eq(OrderEntity::getOrderNo,vendoutData.getOrderNo())
                .set(OrderEntity::getStatus, contract.isSuccess()?ORDER_STATUS_VENDOUT_SUCCESS:ORDER_STATUS_VENDOUT_FAIL)
        );

    }
}
